#!/bin/bash

dl_path='/basic/mysql'

dl_unzip() {
  mkdir $dl_path
  cd $dl_path || exit
  local tarFile
  tarFile='mysql-8.0.17.tar.xz'
  wget -O $tarFile https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.17-linux-glibc2.12-x86_64.tar.xz

  if [ -e $tarFile ]; then
    tar -xvf $tarFile
    rm -rf $tarFile
    mv mysql-8.0.17-linux-glibc2.12-x86_64 mysql-8.0.17
    basedir='/basic/mysql/mysql-8.0.17'

  else
    echo '下载mysql压缩包失败'
    exit
  fi
}

add_config_file() {
  mkdir -p '/data/mysql'
  mkdir -p '/tmp/mysql'
  mkdir -p '/log/mysql/error'

  local myCnf
  myCnf='/etc/my.cnf'
  rm -rf $myCnf

  cat << 'EOF' >> $myCnf

[client]
port=3306
socket=/tmp/mysql/mysql.sock
[mysqld]
port=3306
user=root
socket=/tmp/mysql/mysql.sock
pid-file=/basic/mysql/mysql.pid
basedir=/basic/mysql/mysql-8.0.17
datadir=/data/mysql
log-error=/log/mysql/error/error.log
lower_case_table_names=1
EOF
}

install(){
  #十年绿婚之--basedir写成了- -basedir
  # 0：区分大小写，Linux默认 1：不区分，且命名表名时一律转为小写，Windows默认
  # 2：不区分，但是命名表名时允许大写。所以得改为1，这里和my.cnf都要改
  #二十年绿婚血与泪之lower_case_table_names没加--
  cd $basedir/bin || exit
  ./mysqld --initialize --user=root --basedir=/basic/mysql/mysql-8.0.17 \
  --datadir=/data/mysql/ --lower_case_table_names=1

  #本地客户端软连接
  ln -s /basic/mysql/mysql-8.0.17/bin/mysql mysql
}

start(){
  cd $basedir/support-files || exit
  ./mysql.server start
}



dl_unzip
add_config_file
install
start

#通过查看/log/mysql/error/error.log获取Mysql的初始化密码，并登录mysql
#通过下面的语句可以修改root用户的密码
#
#ALTER USER 'root'@'localhost' IDENTIFIED BY 'root_123';
#为远程登录创建用户,并赋权
#
#CREATE USER 'root'@'%' IDENTIFIED BY 'root_123';
#GRANT ALL ON  *.*  TO 'root'@'%';
#FLUSH PRIVILEGES;

open_port(){
  firewall-cmd --zone=public --add-port=3306/tcp --permanent
  firewall-cmd --reload
}

self_start(){
  cp /basic/mysql/mysql-8.0.17/support-files/mysql.server /etc/init.d/mysqld
  #增加自启
  chkconfig --add mysqld
  #调整启动级别
  chkconfig --level 123456 mysqld on
}
open_port
self_start